package com.ruoyi.swla2.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.swla2.domain.DfqFreeze;
import com.ruoyi.swla2.domain.Terminals;
import com.ruoyi.swla2.model.FreezeDataQueryModel;
import com.ruoyi.swla2.model.MultiTerminalDataModel;
import com.ruoyi.swla2.model.TerminalsModel;
import com.ruoyi.swla2.model.ZoneJoinModel;
import com.ruoyi.swla2.service.IZoneJoinService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.swla2.domain.TerminalHistoryData;
import com.ruoyi.swla2.service.ITerminalHistoryDataService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 大表-历史数据Controller
 *
 * @author gdqt
 * @date 2023-09-11
 */
@RestController
@RequestMapping("/swla2/terminalHistoryData")
public class TerminalHistoryDataController extends BaseController {
    @Autowired
    private ITerminalHistoryDataService terminalHistoryDataService;

    @Autowired
    private IZoneJoinService zoneJoinService;

    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:list')")
    @GetMapping("/getDfqDmaSupplyMonitorData")
    public AjaxResult getDfqDmaSupplyMonitorData(@RequestParam Map<String, Object> paramMap) {
        Map<String, Object> resultMap = new HashMap<>();

        String startDate, endDate;
        Object queryDates = paramMap.get("queryDates");
        if (queryDates == null) {
            startDate = LocalDate.now().minusDays(7L).toString();
            endDate = LocalDate.now().minusDays(1L).toString();
        } else {
            String[] dates = queryDates.toString().split(",");
            startDate = dates[0];
            endDate = dates[1];
        }

        String startDateTime = startDate + " 00:00:00";
        String endDateTime = endDate + " 23:59:59";

        List<ZoneJoinModel> zoneJoinModels = this.getZoneJoinList(paramMap);

        List<TerminalHistoryData> totalDataList = new ArrayList<>();
        Map<String, List<TerminalHistoryData>> dataMapList = new HashMap<>();
        zoneJoinModels.forEach(zj -> {
            TerminalHistoryData thd = new TerminalHistoryData();
            thd.setTerminalID(zj.getTerminalId());
            thd.setReadDateStart(startDateTime);
            thd.setReadDateEnd(endDateTime);
            List<TerminalHistoryData> tmpList = terminalHistoryDataService.selectTerminalHistoryDataList(thd);
            totalDataList.addAll(tmpList);
            dataMapList.put(zj.getTerminalId(), tmpList);
        });

        List<String> timeList = new ArrayList<>();
        dataMapList.forEach((key, dList) -> {
            dList.forEach(d -> {
//                String formatTime = DateUtil.format(d.getReadDate(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
                String formatTime = DateUtil.format(d.getReadDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                if (!timeList.contains(formatTime)) {
                    timeList.add(formatTime);
                }
            });
        });
        resultMap.put("timeList", timeList);

        List<Double> pressureValueList = new ArrayList<>();
        Map<String, BigDecimal> pressDataMap = totalDataList.stream().collect(Collectors.toMap(item -> {
//            System.out.println(DateUtil.format(item.getReadDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            return DateUtil.format(item.getReadDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        }, item -> {
//            System.out.println(item.getPressure());
            return item.getPressure() == null || item.getPressure().doubleValue() < 0 ? BigDecimal.ZERO : item.getPressure();
        }, BigDecimal::add));
        timeList.forEach(time -> pressureValueList.add(pressDataMap.get(time).divide(new BigDecimal(zoneJoinModels.size()), 2, RoundingMode.HALF_UP).doubleValue()));
        resultMap.put("pressList", pressureValueList);

        Map<String, List<ZoneJoinModel>> groupZoneJoinModels = zoneJoinModels.stream().collect(Collectors.groupingBy(ZoneJoinModel::getUsed));

        groupZoneJoinModels.forEach((key, kzjList) -> {
            Set<String> tidSet = kzjList.stream().map(ZoneJoinModel::getTerminalId).collect(Collectors.toSet());
            List<TerminalHistoryData> keyDataList = new ArrayList<>();
            tidSet.forEach(tid -> keyDataList.addAll(dataMapList.get(tid)));
            Map<String, BigDecimal> keyDataMap = keyDataList.stream().collect(Collectors.toMap(item -> DateUtil.format(item.getReadDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), TerminalHistoryData::getInstantNumber, BigDecimal::add));
            List<Double> keyValueList = new ArrayList<>();
            timeList.forEach(time -> {
                keyValueList.add(keyDataMap.get(time) == null ? 0D : keyDataMap.get(time).doubleValue());
            });
            if (key.equals("3")) {
                resultMap.put("outlet", keyValueList);
            } else if (key.equals("4")) {
                resultMap.put("inlet", keyValueList);
            }
        });

        return AjaxResult.success(resultMap);
    }

    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:list')")
    @GetMapping("/getDyhThreeDaysFlowData")
    public AjaxResult getDyhThreeDaysFlowData(@RequestParam Map<String, Object> requestMap) {
        Map<String, Object> resultMap = new HashMap<>();

        String startDate, endDate;
        Object queryDates = requestMap.get("queryDates");
        if (queryDates == null) {
            startDate = LocalDate.now().minusDays(2L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
            endDate = LocalDate.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
        } else {
            String[] dates = queryDates.toString().split(",");
            startDate = dates[0];
            endDate = dates[1];
        }

        List<ZoneJoinModel> zoneJoinModels = this.getZoneJoinList(requestMap);
        if (CollUtil.isNotEmpty(zoneJoinModels)) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("terminalIdList", zoneJoinModels.stream().map(ZoneJoinModel::getTerminalId).collect(Collectors.toList()));
            paramMap.put("startDate", startDate + " 00:00:00");
            paramMap.put("endDate", endDate + " 23:59:59");

            List<TerminalHistoryData> terminalHistoryDataList = terminalHistoryDataService.selectByParamMap(paramMap);
            if (CollUtil.isNotEmpty(terminalHistoryDataList)) {
                Map<String, List<TerminalHistoryData>> dateMapList = terminalHistoryDataList.stream().collect(Collectors.groupingBy(item -> DateUtil.format(item.getReadDate(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))));
                resultMap.putAll(dateMapList);
            }
        }

        return AjaxResult.success(resultMap);
    }

    /**
     * 查询大表-历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:list')")
    @GetMapping("/getAll")
    public AjaxResult getAll(TerminalHistoryData terminalHistoryData) {
        List<TerminalHistoryData> list = terminalHistoryDataService.selectTerminalHistoryDataList(terminalHistoryData);
        return success(list);
    }

    /**
     * 查询大表-历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:list')")
    @GetMapping("/list")
    public TableDataInfo list(TerminalHistoryData terminalHistoryData) {
        startPage();
        List<TerminalHistoryData> list = terminalHistoryDataService.selectTerminalHistoryDataList(terminalHistoryData);
        return getDataTable(list);
    }

    /**
     * 导出大表-历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:export')")
    @Log(title = "大表-历史数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TerminalHistoryData terminalHistoryData) {
        List<TerminalHistoryData> list = terminalHistoryDataService.selectTerminalHistoryDataList(terminalHistoryData);
        ExcelUtil<TerminalHistoryData> util = new ExcelUtil<TerminalHistoryData>(TerminalHistoryData.class);
        util.exportExcel(response, list, "大表-历史数据数据");
    }

    /**
     * 获取大表-历史数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:query')")
    @GetMapping(value = "/{TerminalID}")
    public AjaxResult getInfo(@PathVariable("TerminalID") String TerminalID) {
        return success(terminalHistoryDataService.selectTerminalHistoryDataByTerminalID(TerminalID));
    }

    /**
     * 新增大表-历史数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:add')")
    @Log(title = "大表-历史数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TerminalHistoryData terminalHistoryData) {
        terminalHistoryData.setTenantId(this.getTenantId());
        return toAjax(terminalHistoryDataService.insertTerminalHistoryData(terminalHistoryData));
    }

    /**
     * 修改大表-历史数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:edit')")
    @Log(title = "大表-历史数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TerminalHistoryData terminalHistoryData) {
        return toAjax(terminalHistoryDataService.updateTerminalHistoryData(terminalHistoryData));
    }

    /**
     * 删除大表-历史数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:terminalsFreeze:remove')")
    @Log(title = "大表-历史数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{TerminalIDs}")
    public AjaxResult remove(@PathVariable String[] TerminalIDs) {
        return toAjax(terminalHistoryDataService.deleteTerminalHistoryDataByTerminalIDs(TerminalIDs));
    }

    private List<ZoneJoinModel> getZoneJoinList(Map<String, Object> paramMap) {
        ZoneJoinModel model = new ZoneJoinModel();
        model.setAreaId(paramMap.get("areaId").toString());
        model.setTerminalMark(1);
        return zoneJoinService.getZoneJoinTerminals(model);
//        System.out.println(JSON.toJSONString(zoneJoinModels));

    }

    /**
     * @Description: 获取多表压力数值
     * @date: 2025/2/25 10:24
     * @author: zt
     */
    @GetMapping("/getMultiTerminalDataList")
    public TableDataInfo getMultiTerminalDataList(TerminalsModel model) {
        List<MultiTerminalDataModel> list = terminalHistoryDataService.getMultiTerminalDataList(model);
        return getManualDataTable(list);
    }

    /**
     * @Description: 获取多表压力数值
     * @date: 2025/2/25 10:24
     * @author: zt
     */
    @GetMapping("/getMultiTerminalDataChart")
    public AjaxResult getMultiTerminalDataChart(TerminalsModel model) {
        return terminalHistoryDataService.getMultiTerminalDataChart(model);
    }
}
